package com.ruoyi.web.controller.nongjt;

import com.ruoyi.nongjt.dto.ChangePasswordRequest;
import com.ruoyi.nongjt.dto.LoginRequest;
import com.ruoyi.nongjt.dto.RegisterRequest;
import com.ruoyi.nongjt.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    // 发送验证码
    @PostMapping("/send-code")
    public ResponseEntity<String> sendCode(@RequestParam String email) {
        userService.sendVerificationCode(email);
        return ResponseEntity.ok("验证码已发送");
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<String> register(@Valid @RequestBody RegisterRequest request) {
        String result = userService.register(request);
        if (result.equals("注册成功")) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<String> login(@Valid @RequestBody LoginRequest request) {
        String result = userService.login(request);
        if (result.equals("登录成功")) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.status(401).body(result);
        }
    }

    // 修改密码
    @PutMapping("/change-password")
    public ResponseEntity<String> changePassword(@Valid @RequestBody ChangePasswordRequest request) {
        try {
            String result = userService.changePassword(request);
            if ("密码修改成功".equals(result)) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("密码修改失败: " + e.getMessage());
        }
    }

}
